package org.jvnet.hudson.client_demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Calendar;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class CreateJob {
 
	public static void main(String[] args) throws HttpException, IOException, Exception {
		
		final String urlJobStr = "http://10.144.97.100:8080/jenkins/api/xml";
		final String urlStr = "http://10.144.97.100:8080/jenkins/createItem?name=";
		final String svnUrl = "https://10.144.136.56/svndps_test/dpssvn02/";
		final String jobName = "MR_BL_MOrderSource";
		
		SAXReader reader = new SAXReader();
		Document document = reader.read(new FileInputStream(new File("C:\\Users\\Arthur\\Dropbox\\Arthur\\wsElegance\\sysflow2\\src\\main\\resources\\createTemplate.xml")));
		
		document.getRootElement().element("scm").element("locations").element("hudson.scm.SubversionSCM_-ModuleLocation").element("remote").setText(svnUrl+jobName);
		
		PostMethod postMethod = new PostMethod(urlStr+jobName);
		postMethod.setRequestHeader("Content-type","application/xml; charset=UTF-8");
		postMethod.setRequestBody(new FileInputStream( saveToFile(new File("tmp"+System.currentTimeMillis()+".xml"),document) ));
		
		HttpClient client = new HttpClient();
		int returnCode = client.executeMethod(postMethod);
		System.out.println( returnCode );
	}
	private static File saveToFile(File storedFile,Document document) {
		if (storedFile.exists())
			storedFile.delete();

		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		XMLWriter writer = null;
		try {
			storedFile.createNewFile();

			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8");
			fos = new FileOutputStream(storedFile);
			osw = new OutputStreamWriter(fos, Charset.forName("utf-8"));
			writer = new XMLWriter(osw, format);
			writer.write(document);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) writer.close();
				if (osw != null) osw.close();
				if (fos != null) fos.close();
			} catch (IOException e) {
			}
		}
		return storedFile;
	}
}
